﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SmartRfMng.appcode;
using Newtonsoft.Json;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Globalization;
using BT_Printer;


namespace SmartRfMng
{
    public partial class frmWslDh : Form
    {
        string langue = CultureInfo.CurrentCulture.ToString();

        DataTable dt = new DataTable();
        DataTable dtpay = new DataTable();
        DataTable dtlist = new DataTable();
        DataTable dtshow = new DataTable();

        //客户
        DataTable dtetp = new DataTable();
        //员工
        DataTable dtuser = new DataTable();
        //车辆
        DataTable dttruck = new DataTable();

        private bool CanDoNext = true;
        //当前商品
        string currPluID = string.Empty;
        string currPluCode = string.Empty;
        string currPluName = string.Empty;
        string currPluType = string.Empty;
        string currUnit = string.Empty;

        float currCount = 0;
        float currPfPrice = 0;
        bool rowfound = false;
        int currow = -1;
        int currowsel = 0;
        string curretptype = string.Empty; //当前客户类型
        string currEmpId = string.Empty;//当前用户ID
        List<PluPacket> currListPluPacket = null;
        PluInfo currPluInfo = null;
        float currfKyCount = 0; //当前商品库存

        string currPaytype = string.Empty;
        string currPayNo = string.Empty;
        string currPayTotal = string.Empty;
        int currowpay = -1;
        bool payfound = false;
        float payedtotal = 0;
        string currBillNo = string.Empty;
        string curretp = string.Empty;

        public frmWslDh()
        {
            InitializeComponent();
            CanDoNext = true;

            InitDatagrid(dt);   
            rowfound = false;
            payfound = false;
            btnUp.Enabled = true;
            txtYwyCode.Text = SmartVar.UserCode + "-" + SmartVar.UserName;
            txtYwyCode.Enabled = false;
            //txtSender.Enabled = false;
            //txtPluCode.Enabled = false;
            //txtPfCount.Enabled = false;
            //txtPfPrice.Enabled = false;

            Initdtuser(dtuser);
            Initdtetp(dtetp);
            InitgridselEtp(dtetp);
            InitgridselUser(dtuser);
            Initdttruck(dttruck);
            Initgridtruck(dttruck);
            InitGridList(dtlist);
            InitGridShow(dtshow);

            this.gridselUser.Visible = false;
            this.gridtruck.Visible = false;
            this.gridList.Visible = false;

            pnlHead.Top = 0;
            pnlHead.Left = 0;
            pnlHead.Visible = true;
            txtEtpCode.Focus();

            pnlBody.Visible = false;
            pnlBody.Top = 0;
            pnlBody.Left = 0;

            //初始化支付信息
            InitGridPay(dtpay);
            txtSsTotal.Enabled = false;
            pnlPayinfo.Visible = false;
            pnlPayinfo.Top = 0;
            pnlPayinfo.Left = 0;
 
            btnUp.Visible = false;
            btnpay.Visible = false;
            btnPluType.Text = "正品";
            lblpluname.Text = "";
            txtPackQty.Enabled = false;
            lblShow.Text = "";
            txtPassWd.Enabled = false;

            pnlshow.Visible = false;
            pnlshow.Top = 0;
            pnlshow.Left = 0;

            btnUpPay.Visible = false;
            btnUpPay.Left = btnUp.Left;
            btnUpPay.Top = btnUp.Top;
            //lblShow.Visible = false;
        }

        //初始化客户
        private void Initdtetp(DataTable dt)
        {
            //新建列
            DataColumn col1 = new DataColumn("客户编码", typeof(string));
            DataColumn col2 = new DataColumn("客户名称", typeof(string));
            DataColumn col3 = new DataColumn("类型", typeof(string));

            //添加列
            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);


            if (SmartVar.l_EtpCustInfo != null && SmartVar.l_EtpCustInfo.Count > 0)
            {
                foreach (EtpCustInfo etpinfo in SmartVar.l_EtpCustInfo)
                {
                    //新建行
                    DataRow row = dt.NewRow();

                    //行赋值
                    row["客户编码"] = etpinfo.EtpCode;
                    row["客户名称"] = etpinfo.EtpName;
                    if (etpinfo.EtpType == "3")
                    {
                        row["类型"] = "流通";
                    }
                    else
                    {
                        row["类型"] = "商超";
                    }
                    
                    //添加行
                    dt.Rows.InsertAt(row, 0);
                }
            }
        }

        private void InitgridselEtp(DataTable dt)
        {
            //数据绑定
            this.gridsel.DataSource = dt;

            //设置属性
            DataGridTableStyle tablestyle = new DataGridTableStyle();
            this.gridsel.TableStyles.Add(tablestyle);
            this.gridsel.TableStyles[0].GridColumnStyles[0].Width = 60;
            this.gridsel.TableStyles[0].GridColumnStyles[1].Width = 120;
            this.gridsel.TableStyles[0].GridColumnStyles[2].Width = 56;
        }

        //初始化员工
        private void Initdtuser(DataTable dt)
        {
            //新建列
            DataColumn col1 = new DataColumn("员工ID", typeof(string));
            DataColumn col2 = new DataColumn("员工编码", typeof(string));
            DataColumn col3 = new DataColumn("员工姓名", typeof(string));

            //添加列
            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);

            if (SmartVar.l_UsrEmployee != null && SmartVar.l_UsrEmployee.Count > 0)
            {
                foreach (UsrEmployee user in SmartVar.l_UsrEmployee)
                {
                    //新建行
                    DataRow row = dt.NewRow();

                    //行赋值
                    row["员工ID"] = user.EmpId.ToString();
                    row["员工编码"] = user.EmpCode;
                    row["员工姓名"] = user.EmpName;
                    
                    //添加行
                    dt.Rows.InsertAt(row, 0);
                }
            }
        }

        private void InitgridselUser(DataTable dt)
        {
            //数据绑定
            this.gridselUser.DataSource = dt;

            //设置属性
            DataGridTableStyle tablestyle = new DataGridTableStyle();
            this.gridselUser.TableStyles.Add(tablestyle);
            this.gridselUser.TableStyles[0].GridColumnStyles[0].Width = 0;
            this.gridselUser.TableStyles[0].GridColumnStyles[1].Width = 60;
            this.gridselUser.TableStyles[0].GridColumnStyles[2].Width = 160;
        }


        //初始化车辆
        private void Initdttruck(DataTable dt)
        {
            //新建列
            DataColumn col1 = new DataColumn("车牌号", typeof(string));

            //添加列
            dt.Columns.Add(col1);

            if (SmartVar.l_DspTruck != null && SmartVar.l_DspTruck.Count > 0)
            {
                foreach (DspTruck truck in SmartVar.l_DspTruck)
                {
                    //新建行
                    DataRow row = dt.NewRow();

                    //行赋值
                    row["车牌号"] = truck.TruckNo;

                    //添加行
                    dt.Rows.InsertAt(row, 0);
                }
            }
        }

        private void Initgridtruck(DataTable dt)
        {
            //数据绑定
            this.gridtruck.DataSource = dt;

            //设置属性
            DataGridTableStyle tablestyle = new DataGridTableStyle();
            this.gridtruck.TableStyles.Add(tablestyle);
            this.gridtruck.TableStyles[0].GridColumnStyles[0].Width = 180;
        }

        private void InitDatagrid(DataTable dt)
        {
            //新建列
            DataColumn col1 = new DataColumn("商品ID", typeof(string));
            DataColumn col2 = new DataColumn("商品编码", typeof(string));
            DataColumn col3 = new DataColumn("商品名称", typeof(string));
            DataColumn col4 = new DataColumn("单位", typeof(string)); 
            DataColumn col5 = new DataColumn("批发数量", typeof(float));
            DataColumn col6 = new DataColumn("批发价格", typeof(float));
            DataColumn col7 = new DataColumn("类型", typeof(string));

            //添加列
            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);
            dt.Columns.Add(col4);
            dt.Columns.Add(col5);
            dt.Columns.Add(col6);
            dt.Columns.Add(col7);

            //数据绑定
            this.dbgrid.DataSource = dt;

            //设置属性
            DataGridTableStyle tablestyle = new DataGridTableStyle();
            this.dbgrid.TableStyles.Add(tablestyle);
            this.dbgrid.TableStyles[0].GridColumnStyles[0].Width = 0;
            this.dbgrid.TableStyles[0].GridColumnStyles[1].Width = 56;
            this.dbgrid.TableStyles[0].GridColumnStyles[2].Width = 160;
            this.dbgrid.TableStyles[0].GridColumnStyles[3].Width = 56;
            this.dbgrid.TableStyles[0].GridColumnStyles[4].Width = 56;
            this.dbgrid.TableStyles[0].GridColumnStyles[5].Width = 56;
            this.dbgrid.TableStyles[0].GridColumnStyles[6].Width = 56;

        }

        private void InitGridPay(DataTable dt)
        {
            //新建列
            DataColumn col1 = new DataColumn("付款方式", typeof(string));
            DataColumn col2 = new DataColumn("支付号", typeof(string));
            DataColumn col3 = new DataColumn("支付金额", typeof(float));
            DataColumn col4 = new DataColumn("状态", typeof(float));

            //添加列
            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);
            dt.Columns.Add(col4);

            //数据绑定
            this.dbgridpay.DataSource = dt;

            //设置属性
            DataGridTableStyle tablestyle = new DataGridTableStyle();
            this.dbgridpay.TableStyles.Add(tablestyle);
            this.dbgridpay.TableStyles[0].GridColumnStyles[0].Width = 76;
            this.dbgridpay.TableStyles[0].GridColumnStyles[1].Width = 160;
            this.dbgridpay.TableStyles[0].GridColumnStyles[2].Width = 62;
            this.dbgridpay.TableStyles[0].GridColumnStyles[3].Width = 0;
        }

        private void InitGridList(DataTable dt)
        {
            //新建列
            DataColumn col1 = new DataColumn("单号", typeof(string));
            DataColumn col2 = new DataColumn("录入日期", typeof(string));
            DataColumn col3 = new DataColumn("客户", typeof(string));
            DataColumn col4 = new DataColumn("业务员", typeof(string));
            DataColumn col5 = new DataColumn("实收金额", typeof(float));
            DataColumn col6 = new DataColumn("欠款金额", typeof(float));
            
            //添加列
            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);
            dt.Columns.Add(col4);
            dt.Columns.Add(col5);
            dt.Columns.Add(col6);

            //数据绑定
            this.gridList.DataSource = dt;

            //设置属性
            DataGridTableStyle tablestyle = new DataGridTableStyle();
            this.gridList.TableStyles.Add(tablestyle);
            this.gridList.TableStyles[0].GridColumnStyles[0].Width = 80;
            this.gridList.TableStyles[0].GridColumnStyles[1].Width = 76;
            this.gridList.TableStyles[0].GridColumnStyles[2].Width = 156;
            this.gridList.TableStyles[0].GridColumnStyles[3].Width = 62;
            this.gridList.TableStyles[0].GridColumnStyles[4].Width = 62;
            this.gridList.TableStyles[0].GridColumnStyles[5].Width = 62;
        }

        private void AddPluRow(DataTable dt)
        {
            if (!rowfound)
            {
                //新建行
                DataRow row = dt.NewRow();

                //行赋值
                row["商品ID"] = currPluID;
                row["商品编码"] = currPluCode;
                row["商品名称"] = currPluName;
                row["单位"] = currUnit;
                row["批发数量"] = currCount;
                row["批发价格"] = currPfPrice;
                row["类型"] = currPluType;

                //添加行
                dt.Rows.InsertAt(row, 0);

                dbgrid.CurrentRowIndex = 0;
            }
            else
            {
                if (currow < 0) return;
                DataRow dr = dt.Rows[currow];
                dr["批发数量"] = currCount;
                dr["批发价格"] = currPfPrice;
            }

           // lblShow.Text = dt.Rows.Count.ToString();
        }


        private void InitGridShow(DataTable dt)
        {
            //新建列
            DataColumn col1 = new DataColumn("商品ID", typeof(string));
            DataColumn col2 = new DataColumn("商品编码", typeof(string));
            DataColumn col3 = new DataColumn("商品名称", typeof(string));
            DataColumn col4 = new DataColumn("单位", typeof(string));
            DataColumn col5 = new DataColumn("批发数量", typeof(float));
            DataColumn col6 = new DataColumn("批发价格", typeof(float));
            DataColumn col7 = new DataColumn("类型", typeof(string));

            //添加列
            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);
            dt.Columns.Add(col4);
            dt.Columns.Add(col5);
            dt.Columns.Add(col6);
            dt.Columns.Add(col7);

            //数据绑定
            this.gridshow.DataSource = dt;

            //设置属性
            DataGridTableStyle tablestyle = new DataGridTableStyle();
            this.gridshow.TableStyles.Add(tablestyle);
            this.gridshow.TableStyles[0].GridColumnStyles[0].Width = 0;
            this.gridshow.TableStyles[0].GridColumnStyles[1].Width = 56;
            this.gridshow.TableStyles[0].GridColumnStyles[2].Width = 160;
            this.gridshow.TableStyles[0].GridColumnStyles[3].Width = 56;
            this.gridshow.TableStyles[0].GridColumnStyles[4].Width = 56;
            this.gridshow.TableStyles[0].GridColumnStyles[5].Width = 56;
            this.gridshow.TableStyles[0].GridColumnStyles[6].Width = 56;
        }

        private void btnexit_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定要退出批发订单吗？", "客户分销", MessageBoxButtons.YesNo,
               MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dr == DialogResult.Yes)
            {
                this.Close();
            }
        }


        private void btnUp_Click(object sender, EventArgs e)
        {
            if (txtEtpCode.Text.Trim() == "" || txtEtpCode.Text.IndexOf('-') <= 0)
            {
                MessageBox.Show("必须选择批发客户！", "客户分销", MessageBoxButtons.OK,
                     MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }

            //if (txtSender.Text.Trim() == "" || txtSender.Text.IndexOf('-') <= 0)
            //{
            //    MessageBox.Show("必须选择送货员！", "客户分销", MessageBoxButtons.OK,
            //         MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
            //    return;
            //}

            //if (txtTruck.Text.Trim() == "")
            //{
            //    MessageBox.Show("必须指定车牌！", "客户分销", MessageBoxButtons.OK,
            //         MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
            //    return;
            //}

            if (dt.Rows.Count <= 0)
            {
                MessageBox.Show("批发商品为空，不允许上传！", "客户分销", MessageBoxButtons.OK,
                      MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }

            //进行批发金额合计
            double fSsTotal = 0;
            foreach (DataRow dr in dt.Rows)
            {
                fSsTotal = fSsTotal + Math.Round(float.Parse(dr["批发数量"].ToString())
                    * float.Parse(dr["批发价格"].ToString()) * 100) / 100;
            }
            txtSsTotal.Text = fSsTotal.ToString();

            //判断是否完成支付
            //payedtotal = 0;
            //foreach (DataRow dr in dtpay.Rows)
            //{
            //    payedtotal = payedtotal + float.Parse(dr["支付金额"].ToString());
            //}

            //if (float.Parse(txtSsTotal.Text) - payedtotal > 0)
            //{
            //    MessageBox.Show("未完成付款，不允许上传！", "客户分销", MessageBoxButtons.OK,
            //          MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
            //    return;
            //}

            DialogResult dialog = MessageBox.Show("确定要上传该批发订单吗？", "客户分销", MessageBoxButtons.YesNo,
               MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dialog != DialogResult.Yes)
            {
                return;
            }

            //进行上传
            WslPfXsHead xshead = new WslPfXsHead();
            xshead.BillNo = "";
            string sEtpCode =  txtEtpCode.Text.Trim();
            if (sEtpCode.IndexOf('-') > 0)
            {
                xshead.EtpCode = sEtpCode.Substring(0, sEtpCode.IndexOf('-'));
            }
            
            xshead.LrDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            xshead.YwyCode = SmartVar.UserCode;
            string sSender = txtSender.Text.Trim();
            if (sSender.IndexOf('-') > 0)
            {
                xshead.ShyCode = sSender.Substring(0, sSender.IndexOf('-'));
            }
            xshead.TrunckNo = txtTruck.Text.Trim();
            //0-批发销售；1-批发退货；2-批发订货； 3-无批发单退货 4-不管库存联销商品批发
            xshead.BillType = "2";
            xshead.RFNO = SmartVar.RFNO;

            int i = 1;
            foreach (DataRow dr in dt.Rows)
            {
                WslPfXsBody wslpfxsbody = new WslPfXsBody();
                wslpfxsbody.SerialNo = i;
                wslpfxsbody.PluID = Int64.Parse(dr["商品ID"].ToString());
                wslpfxsbody.PfCount = float.Parse(dr["批发数量"].ToString());
                wslpfxsbody.HJPrice = float.Parse(dr["批发价格"].ToString());
                // 0-正品  1-赠品  2-促销品  3-不良品
                if (dr["类型"].ToString() == "正品")
                {
                    wslpfxsbody.PluType = "0";
                }
                else if (dr["类型"].ToString() == "赠品")
                {
                    wslpfxsbody.PluType = "1";
                }
                xshead.lstWslPfXsBody.Add(wslpfxsbody);
                i = i + 1;
            }

            i = 1;
            foreach (DataRow dr in dtpay.Rows)
            {
                WslPfXsPay xspay = new WslPfXsPay();
                xspay.SerialNo = i;
                string sPayType = dr["付款方式"].ToString();
                if (sPayType.IndexOf('-') > 0)
                {
                    xspay.Paytype = sPayType.Substring(0, sPayType.IndexOf('-'));
                }
                xspay.PayNo = dr["支付号"].ToString();
                xspay.PayTotal = float.Parse(dr["支付金额"].ToString());
                xshead.lstWslPfXsPay.Add(xspay);
                i = i + 1;
            }

            StoreRf rf = new StoreRf();
            string sRtnMsg = string.Empty;
            int iRtnCode = rf.DealWslPfXs(xshead, out sRtnMsg);
            if (iRtnCode == 0)
            {
                btnUp.Enabled = false;

                //进行小票打印
                StringBuilder sb = new StringBuilder();
                sb.Append(" \r\n");
                sb.Append(" \r\n");
                sb.Append("    肥城达润兴批发订单    \r\n");
                sb.Append("客户：" + sEtpCode + " \r\n");
                sb.Append("业务员：" + txtYwyCode.Text.Trim()  + " \r\n");
                sb.Append(" 送货员：" + txtSender.Text.Trim()  + " \r\n");
                sb.Append("车牌号：" + txtTruck.Text.Trim() + " \r\n");
                sb.Append("--------------------------\r\n");
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("品名：" + dr["商品编码"].ToString() + " " + dr["商品名称"].ToString() + "\r\n");
                    sb.Append("单位：" + dr["单位"].ToString() 
                        + " 数量：" + dr["批发数量"].ToString()
                        + " 价格：" + dr["批发价格"].ToString() + "\r\n");
                }
                sb.Append("------------------------- \r\n");
                sb.Append("合计应收：" + txtSsTotal.Text.Trim() + "\r\n");
                //foreach (DataRow dr in dtpay.Rows)
                //{
                //    sb.Append("支付方式：" + dr["付款方式"].ToString() + " " + dr["支付金额"].ToString() + "\r\n");
                //}
                sb.Append(" \r\n");
                sb.Append(" \r\n");

                string sWriteData = sb.ToString();

                BillPrint(sWriteData);

                MessageBox.Show("上传批发订单成功！", "客户分销", MessageBoxButtons.OK,
                     MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                txtPluCode.Text = "";
                txtPackCount.Text = "";
                txtPfCount.Text = "";
                txtPfPrice.Text = "";
                dtpay.Clear();
                dtpay = null;
                dt.Clear();
                dt = null;
                xshead.lstWslPfXsBody.Clear();
                xshead.lstWslPfXsBody = null;
                xshead.lstWslPfXsPay.Clear();
                xshead.lstWslPfXsPay = null;
                xshead = null;

                txtEtpCode.Text = "";
                txtSender.Text = "";
                txtTruck.Text = "";
                return;
            }
            else
            {
                MessageBox.Show("上传批发订单失败！" + (char)13 + sRtnMsg, "客户分销", MessageBoxButtons.OK,
                    MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
                return;
            }
        }

        private void btndelete_Click(object sender, EventArgs e)
        {
            if (dt.Rows.Count > 0 && currow >= 0)
            {
                dt.Rows[currow].Delete();
                currow = -1;
                currPluID = "";
                currPluCode = "";
                currPluName = "";
                currCount = 0;
                currPfPrice = 0;
                currPluType = "";
                currUnit = "";

                txtPackQty.Text = "0";
                txtPackCount.Text = "";
                txtPluCode.Text = "";
                lblpluname.Text = "";
                txtPfCount.Text = "";
                txtPfPrice.Text = "";
                lblShow.Text = "";
                txtPluCode.Focus();
               // lblShow.Text = dt.Rows.Count.ToString();
            }
        }

        private void txtPluCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                cmbPackUnit.Items.Clear();
                string sPluCode = txtPluCode.Text.Trim();
                if (sPluCode != "")
                {
                    if (SmartVar.l_PluInfo != null && SmartVar.l_PluInfo.Count > 0)
                    {
                        bool bfound = false;
                        foreach (PluInfo pluinfo in SmartVar.l_PluInfo)
                        {
                            lblpluname.ForeColor = Color.Blue;
                            if (pluinfo.PluCode == sPluCode || pluinfo.ListPluBarCode.IndexOf(sPluCode) >= 0)
                            {
                                rowfound = false;
                                currPluInfo = pluinfo;
                                currPluID = pluinfo.PluID.ToString();
                                currPluCode = pluinfo.PluCode;
                                txtPluCode.Text = currPluCode;
                                currPluName = pluinfo.PluName;
                                lblpluname.Text = currPluName;
                                currPluType = btnPluType.Text;
                                currUnit = pluinfo.Unit;

                                if (currPluType == "赠品")
                                {
                                    currPfPrice = 0;
                                }
                                else
                                {
                                    if (curretptype == "商超")
                                    {
                                        if (pluinfo.UDP10.ToString() == "")
                                        {
                                            currPfPrice = 0;
                                        }
                                        else
                                        {
                                            currPfPrice = float.Parse(pluinfo.UDP10.ToString());
                                        }
                                    }
                                    else
                                    {
                                        if (pluinfo.UDP11.ToString() == "")
                                        {
                                            currPfPrice = 0;
                                        }
                                        else
                                        {
                                            currPfPrice = float.Parse(pluinfo.UDP11.ToString());
                                        }
                                    }
                                
                                }

                                txtPfPrice.Text = currPfPrice.ToString();
                                currListPluPacket = pluinfo.ListPluPacket;
                                foreach (PluPacket plupacket in pluinfo.ListPluPacket)
                                {
                                    cmbPackUnit.Items.Add(plupacket.PackUnit);
                                }

                                if (cmbPackUnit.Items.Count > 0)
                                {
                                    cmbPackUnit.SelectedIndex = 0;
                                }
                                else
                                {
                                    txtPackQty.Text = "0";
                                }

                                txtPackCount.Focus();

                                //查询对应库存
                                StoreRf rf = new StoreRf();
                                string sRtnMsg = string.Empty;
                                //lblShow.Text = "查库存";
                                int iRtnCode = rf.GetKcCount(currPluID, out currfKyCount, out sRtnMsg);
                                if (iRtnCode == 0)
                                {
                                    lblShow.Text = currfKyCount.ToString(); //"库存:"
                                }
                                else
                                {
                                    lblShow.Text = "-1";
                                    lblpluname.ForeColor = Color.Red;
                                    // lblShow.Text = "查询库存失败";
                                    MessageBox.Show("查询商品库存失败！", "客户分销", MessageBoxButtons.OK,
                                       MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                                    return;
                                }
                                bfound = true;
                                break;
                            }
                        }

                        if (!bfound)
                        {
                            currPluInfo = null;
                            lblpluname.Text = "没有找到该商品";
                            lblpluname.ForeColor = Color.Red;
                            txtPluCode.Text = string.Empty;
                            currListPluPacket = null;
                            currPluInfo = null;
                            cmbPackUnit.Items.Clear();
                            txtPackQty.Text = "0";
                            txtPackCount.Text = "";
                            txtPfCount.Text = "";
                            txtPfPrice.Text = "";
                            lblShow.Text = "";
                            txtPluCode.Focus();
                        }
                       
                    }
                }
            }    
        }

        private void txtPfCount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8 && e.KeyChar != (char)13)
            {
                e.Handled = true;
            }
        }

        private void txtPfCount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (txtPfCount.Text.Trim() == "" && txtPackCount.Text.Trim() == "")
                {
                    return;
                }

                if (lblpluname.ForeColor == Color.Red)
                {
                    return;
                }

                if (txtPackQty.Text.Trim() == "")
                {
                    txtPackQty.Text = "0";
                }

                if (txtPackCount.Text.Trim() == "")
                {
                    txtPackCount.Text = "0";
                }
                currCount = float.Parse(txtPfCount.Text.Trim()) 
                    + float.Parse(txtPackQty.Text) * float.Parse(txtPackCount.Text);
                if (currCount <= 0)
                {
                    MessageBox.Show("批发数量不允许为0！", "客户分销", MessageBoxButtons.OK,
                       MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    return;
                }

                //进行库存数量比较
                if (currCount > currfKyCount)
                {
                    MessageBox.Show("批发数量超出库存数量！", "客户分销", MessageBoxButtons.OK,
                       MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    return;
                } 

                AddPluRow(dt);
                txtPluCode.Text = string.Empty;
                lblpluname.Text = "";
                //currListPluPacket = null;
                //currPluInfo = null;
                //cmbPackUnit.Items.Clear();
                txtPackQty.Text = "0";
                txtPackCount.Text = "";
                txtPfCount.Text = "";
                lblShow.Text = "";
                txtPluCode.Focus();
            }
        }


        private void frmWslXs_Closing(object sender, CancelEventArgs e)
        {
            if (dt != null)
            {
                dt.Clear();
                dt = null;
            }

            if (dtlist != null)
            {
                dtlist.Clear();
                dtlist = null;
            }

            if (dtshow != null)
            {
                dtshow.Clear();
                dtshow = null;
            }

            if (dtpay != null)
            {
                dtpay.Clear();
                dtpay = null;
            }

            if (dtetp != null)
            {
                dtetp.Clear();
                dtetp = null;
            }

            if (dtuser != null)
            {
                dtuser.Clear();
                dtuser = null;
            }

            if (dttruck != null)
            {
                dttruck.Clear();
                dttruck = null;
            }

        }

        private void btnpay_Click(object sender, EventArgs e)
        {
            if (btnpay.Text == "付款")
            {
                if (pnlshow.Visible)
                {
                    if (dtshow.Rows.Count <= 0)
                    {
                        MessageBox.Show("批发商品不存在！", "客户分销", MessageBoxButtons.OK,
                           MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                        return;
                    }
                    pnlHead.Visible = false;
                    pnlshow.Visible = false;
                    btnpay.Left = 3;
                    pnlPayinfo.Visible = true;
                    pnlBody.Visible = false;
                    btnpay.Text = "返回";
                    btnRefresh.Visible = false;
                    

                    //进行付款信息查询
                    if (!CanDoNext)
                    {
                        return;
                    }
                    CanDoNext = false;

                    try
                    {
                        string sRtnMsg = string.Empty;
                        StoreRf rf = new StoreRf();
                        bool bResult = rf.QryWslPfXsPayInfo(currBillNo, out sRtnMsg);
                        if (!bResult)
                        {
                            MessageBox.Show("获取批发支付明细失败！", "提示", MessageBoxButtons.OK,
                              MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
                            return;
                        }

                        string CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                        string FileName = CurrentPath + "\\PfDataPay.xml";
                        if (File.Exists(FileName))
                        {
                            FileStream fs = File.OpenRead(FileName);
                            try
                            {
                                byte[] buffer = new byte[fs.Length];
                                fs.Read(buffer, 0, buffer.Length);
                                string sWslPayXML = System.Text.Encoding.Default.GetString(buffer, 0, buffer.Length);
                                List<WslPfXsPayInfo> lsXsPayInfo = JsonConvert.DeserializeObject<List<WslPfXsPayInfo>>(sWslPayXML);
                                if (dtpay != null && dtpay.Rows.Count > 0) dtpay.Clear();
                                foreach (WslPfXsPayInfo xspayinfo in lsXsPayInfo)
                                {
                                    //新建行
                                    DataRow row = dtpay.NewRow();
                                    
                                    //行赋值 
                                    if (xspayinfo.PayType == "0")
                                    {
                                        row["付款方式"] = "0-现金";
                                    }
                                    else if (xspayinfo.PayType == "1")
                                    {
                                        row["付款方式"] = "1-银联卡";
                                    }
                                    else if (xspayinfo.PayType == "2")
                                    {
                                        row["付款方式"] = "2-储值卡";
                                    }
                                    row["支付号"] = xspayinfo.PayNo;
                                    row["支付金额"] = xspayinfo.PayTotal.ToString();
                                    row["状态"] = "1";

                                    //添加行
                                    dtpay.Rows.Add(row);
                                }
                            }
                            finally
                            {
                                fs.Close();
                            }

                            btnUpPay.Visible = false;

                            //进行批发金额合计
                            double fSsTotal = 0;
                            foreach (DataRow dr in dtshow.Rows)
                            {
                                fSsTotal = fSsTotal + Math.Round(float.Parse(dr["批发数量"].ToString())
                                    * float.Parse(dr["批发价格"].ToString()) * 100) / 100;
                            }
                            txtSsTotal.Text = fSsTotal.ToString();
                            cmbPaytype.SelectedIndex = 0;

                            MessageBox.Show("获取批发支付信息成功！", "提示", MessageBoxButtons.OK,
                            MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                            return;
                        }

                    }
                    finally
                    {
                        CanDoNext = true;
                    } 
                }
                else
                {
                    if (dt.Rows.Count <= 0)
                    {
                        txtPluCode.Focus();
                        MessageBox.Show("批发商品不存在！", "客户分销", MessageBoxButtons.OK,
                           MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                        return;
                    }

                    pnlshow.Visible = false;
                    btnpay.Left = 3;
                    pnlPayinfo.Visible = true;
                    pnlBody.Visible = false;
                    btnpay.Text = "返回";
                    btnRefresh.Visible = false;
                    //进行批发金额合计
                    double fSsTotal = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        fSsTotal = fSsTotal + Math.Round(float.Parse(dr["批发数量"].ToString())
                            * float.Parse(dr["批发价格"].ToString()) * 100) / 100;
                    }
                    txtSsTotal.Text = fSsTotal.ToString();
                    cmbPaytype.SelectedIndex = 0;
                }
            }
            else
            {
                btnpay.Left = 58;
                btnRefresh.Visible = true;
                pnlPayinfo.Visible = false;
                btnUpPay.Visible = false;
                if (currBillNo == "")
                {
                    pnlBody.Visible = true;
                }
                else
                {
                    pnlHead.Visible = true;
                    currBillNo = "";
                    btnpay.Visible = false;
                }
                
                btnpay.Text = "付款";
            } 
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            pnlBody.Visible = false;
            pnlHead.Visible = true;
            pnlPayinfo.Visible = false;
            pnlshow.Visible = false;
            btnUpPay.Visible = false;

            if (btnRefresh.Text == "查询")
            {
                txtEtpCode.Text = "";
                //txtSender.Text = "";
                //txtTruck.Text = "";

                btnHeadOK.Text = "刷新";
                btnRefresh.Text = "返回";
                txtEtpCode.Focus();
                //txtSender.Enabled = false;
                //txtTruck.Enabled = false;
                
            }
            else if (btnRefresh.Text == "表头")
            {
                txtSender.Enabled = true;
                txtTruck.Enabled = true;
                btnHeadOK.Text = "确认";
                btnRefresh.Text = "查询";
                txtEtpCode.Focus();
            }
            else
            {
                btnHeadOK.Text = "确认";
                btnRefresh.Text = "查询";
                //txtSender.Enabled = true;
                //txtTruck.Enabled = true;
                pnlHead.Visible = true;
                if (!gridList.Visible)
                {
                    txtEtpCode.Focus();
                }
            } 
        }


        private void txtEtpCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (txtEtpCode.Text != "")
                {
                    if (txtEtpCode.Text.IndexOf('-') < 0)
                    {
                        //根据编码匹配
                        foreach (DataRow dr in dtetp.Rows)
                        {
                            if (dr["客户编码"].ToString().ToUpper() == txtEtpCode.Text.Trim().ToUpper())
                            {
                                txtEtpCode.Text = dr["客户编码"].ToString() + "-"
                                    + dr["客户名称"].ToString();
                                curretptype = dr["类型"].ToString();
                                break;
                            }
                        }
                    }
                    else
                    {
                        txtSender.Focus();
                    }
                } 
            }
        }

        private void txtEtpCode_GotFocus(object sender, EventArgs e)
        {
            txtEtpCode.SelectAll();
            this.gridselUser.Visible = false;
            this.gridtruck.Visible = false;
            this.gridsel.Visible = true;
            this.gridList.Visible = false;
        }

        private void txtSender_GotFocus(object sender, EventArgs e)
        {
            txtSender.SelectAll();
            this.gridsel.Visible = false;
            this.gridtruck.Visible = false;
            this.gridselUser.Visible = true;
            this.gridList.Visible = false;
        }

        private void txtSender_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (txtSender.Text != "")
                {
                    if (txtSender.Text.IndexOf('-') < 0)
                    {
                        //根据编码匹配
                        foreach (DataRow dr in dtuser.Rows)
                        {
                            if (dr["员工编码"].ToString().ToUpper() == txtSender.Text.Trim().ToUpper())
                            {
                                txtSender.Text = dr["员工编码"].ToString() + "-"
                                    + dr["员工姓名"].ToString();
                                currEmpId = dr["员工ID"].ToString();
                                break;
                            }
                        }
                    }
                    else
                    {
                        txtTruck.Focus();
                    }
                }
            }
        }

        private void txtTruck_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (txtTruck.Text != "")
                {
                    //根据编码匹配
                    foreach (DataRow dr in dttruck.Rows)
                    {
                        if (dr["车牌号"].ToString().ToUpper().IndexOf(txtTruck.Text.Trim().ToUpper()) > 0)
                        {
                            txtTruck.Text = dr["车牌号"].ToString();
                            break;
                        }
                    }

                    txtEtpCode.Focus();
                }

            }
        }

        private void txtTruck_GotFocus(object sender, EventArgs e)
        {
            txtTruck.SelectAll();
            this.gridsel.Visible = false;
            this.gridselUser.Visible = false;
            this.gridtruck.Visible = true;
            this.gridList.Visible = false;
        }

        private void btnHeadCancel_Click(object sender, EventArgs e)
        {
            txtEtpCode.Text = "";
            txtSender.Text = "";
            txtTruck.Text = "";
        }

        private void btnHeadOK_Click(object sender, EventArgs e)
        {
            if (btnHeadOK.Text == "确认")
            {
                if (txtEtpCode.Text.Trim() == "")
                {
                    MessageBox.Show("必须选择客户！", "客户分销", MessageBoxButtons.OK,
                       MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    return;
                }

                //if (txtSender.Text.Trim() == "")
                //{
                //    MessageBox.Show("必须选择送货员！", "客户分销", MessageBoxButtons.OK,
                //       MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                //    return;
                //}

                //if (txtTruck.Text.Trim() == "")
                //{
                //    MessageBox.Show("必须选择车牌！", "客户分销", MessageBoxButtons.OK,
                //       MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                //    return;
                //}

                currBillNo = "";
                pnlHead.Visible = false;
                pnlBody.Visible = true;
                btnRefresh.Text = "表头";
                txtPluCode.Focus();
                btnpay.Visible = false;
                btnUp.Visible = true;
                btnUp.Enabled = true; //新单据
            }
            else
            {
                this.gridsel.Visible = false;
                this.gridtruck.Visible = false;
                this.gridselUser.Visible = false;
                this.gridList.Visible = true;
                btnpay.Visible = false;
                btnUp.Visible = false;

                if (!CanDoNext)
                {
                    return;
                }
                CanDoNext = false;

                try
                {
                    string sBillType = "2";
                    string sEtpCode =  txtEtpCode.Text.Trim();
                    if (sEtpCode.IndexOf('-') > 0)
                    {
                        sEtpCode = sEtpCode.Substring(0, sEtpCode.IndexOf('-'));
                    }   
                   
                    string sYwyCode =  SmartVar.UserCode;

                    string sRtnMsg = string.Empty;
                    StoreRf rf = new StoreRf();
                    bool bResult = rf.QryWslPfXsInfo(sEtpCode, sYwyCode, sBillType, out sRtnMsg);
                    if(!bResult)
                    {
                        MessageBox.Show("批发订单查询失败！", "提示", MessageBoxButtons.OK,
                          MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
                        return;
                    }

                    string CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                    string FileName = CurrentPath + "\\PfData.xml";
                    if (File.Exists(FileName))
                    {
                        FileStream fs = File.OpenRead(FileName);
                        try
                        {
                            byte[] buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Length);
                            string sWslXML = System.Text.Encoding.Default.GetString(buffer, 0, buffer.Length);
                            List<WslPfXsInfo> lsXsInfo  = JsonConvert.DeserializeObject<List<WslPfXsInfo>>(sWslXML);
                            
                            dtlist.Clear();
                            foreach (WslPfXsInfo xsinfo in lsXsInfo)
                            {
                                //新建行
                                DataRow row = dtlist.NewRow();

                                //行赋值
                                row["单号"] = xsinfo.BillNo;
                                row["录入日期"] = xsinfo.LrDate;
                                row["客户"] = xsinfo.EtpCode + "-" + xsinfo.EtpName;
                                row["业务员"] = xsinfo.YwyCode + "-" + xsinfo.YwyName;
                                row["实收金额"] = float.Parse(xsinfo.SsTotal.ToString());
                                row["欠款金额"] = float.Parse(xsinfo.QkTotal.ToString());

                                //添加行
                                dtlist.Rows.Add(row);
                            }
                        }
                        finally
                        {
                            fs.Close();
                        }


                        MessageBox.Show("批发订单查询成功！", "提示", MessageBoxButtons.OK,
                        MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                        return;
                    }

                }
                finally
                {
                    CanDoNext = true;
                }
            }
        }

        private void cmbPackUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (currListPluPacket != null && currListPluPacket.Count > 0)
            {
                foreach (PluPacket plupacket in currListPluPacket)
                {
                    if (cmbPackUnit.Text == plupacket.PackUnit)
                    {
                        txtPackQty.Text = plupacket.PackQty.ToString();
                        if (txtPackQty.Text == "")
                        {
                            txtPackQty.Text = "0";
                        }
                        break;
                    }
                }
            }
        }

        private void cmbPackUnit_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)13)
            {
                e.Handled = true;
            }
        }

        private void txtPackCount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                txtPfCount.Focus();
                txtPfCount.SelectAll();
            }
        }

        private void btnPluType_Click(object sender, EventArgs e)
        {
            if (btnPluType.Text == "正品")
            {
                btnPluType.Text = "赠品";
                currPfPrice = 0;
                txtPfPrice.Text = "0";
            }
            else 
            {
                btnPluType.Text = "正品";
                if (currPluInfo != null)
                {
                    if (curretptype == "流通")
                    {
                        if (currPluInfo.UDP10.ToString() == "")
                        {
                            currPfPrice = 0;
                        }
                        else
                        {
                            currPfPrice = float.Parse(currPluInfo.UDP10.ToString());
                        }
                    }
                    else
                    {
                        if (currPluInfo.UDP11.ToString() == "")
                        {
                            currPfPrice = 0;
                        }
                        else
                        {
                            currPfPrice = float.Parse(currPluInfo.UDP11.ToString());
                        }
                    }
                }
                txtPfPrice.Text = currPfPrice.ToString();
            }            
            txtPluCode.Focus();
        }

        private void txtPluCode_GotFocus(object sender, EventArgs e)
        {
            if (txtPluCode.Text == "")
            {
                btnPluType.Text = "正品";
            }
            txtPluCode.SelectAll();
        }

        private void txtPayNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (!txtPassWd.Enabled)
                {
                    txtPayTotal.Focus();
                }
                else
                {
                    txtPassWd.Focus();
                }  
            }
        }

        private void cmbPaytype_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPaytype.SelectedIndex == 2)
            {
                txtPayNo.Text = "";
                txtPassWd.Text = "";
                txtPassWd.Enabled = true;
            }
            else
            {
                txtPayNo.Text = "";
                txtPassWd.Text = "";
                txtPassWd.Enabled = false;
            }

            txtPayNo.Focus();
            txtPayNo.SelectAll();
        }

        private void txtPassWd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                txtPayTotal.Focus();
                txtPayTotal.SelectAll();
            }
        }

        private void AddPayRow(DataTable dt)
        {
            if (!payfound)
            {
                //新建行
                DataRow row = dt.NewRow();

                //行赋值
                row["付款方式"] = currPaytype;
                row["支付号"] = currPayNo;
                row["支付金额"] = currPayTotal;
                row["状态"] = "0";

                //添加行
                dt.Rows.InsertAt(row, 0);

                dbgridpay.CurrentRowIndex = 0;
            }
        }

        private void btnpayOk_Click(object sender, EventArgs e)
        {
            currPaytype = cmbPaytype.Text;
            if (cmbPaytype.Text.Trim() == "")
            {
                MessageBox.Show("必须选择付款方式！", "客户分销", MessageBoxButtons.OK,
                   MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }
            currPayNo = txtPayNo.Text;
            if (txtPayTotal.Text.Trim() == "")
            {
                txtPayTotal.Text = "0";
            }

            float fpaytotal = 0;
            try
            {
                fpaytotal = float.Parse(txtPayTotal.Text);
            }
            catch(Exception ex)
            {
                fpaytotal = 0;
                ex.Message.ToString();
                MessageBox.Show("支付金额错误！", "客户分销", MessageBoxButtons.OK,
                   MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }

            currPayTotal = txtPayTotal.Text;
            payfound = false;


            if (fpaytotal <= 0)
            {
                MessageBox.Show("支付金额必须大于0！", "客户分销", MessageBoxButtons.OK,
                   MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }

            if (fpaytotal > float.Parse(txtSsTotal.Text) - payedtotal)
            {
                MessageBox.Show("支付金额超出应收金额！", "客户分销", MessageBoxButtons.OK,
                   MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            } 

            AddPayRow(dtpay);
            cmbPaytype.SelectedIndex = 0;
            txtPayNo.Text = "";
            txtPassWd.Text = "";
            txtPayTotal.Text = "";
            cmbPaytype.Focus();
        }

        private void btnPayCancel_Click(object sender, EventArgs e)
        {
            if (dtpay.Rows.Count > 0 && currowpay >= 0)
            {
                if (dtpay.Rows[currowpay]["状态"].ToString() == "0")
                {
                    dtpay.Rows[currowpay].Delete();
                    currowpay = -1;
                    currPaytype = "";
                    currPayNo = "";
                    currPayTotal = "";

                    cmbPaytype.SelectedIndex = 0;
                    txtPayNo.Text = "";
                    txtPassWd.Text = "";
                    txtPayTotal.Text = "";
                    cmbPaytype.Focus();
                }
                else
                {
                    MessageBox.Show("该支付已上传，不允许删除！", "客户分销", MessageBoxButtons.OK,
                      MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    return;
                }
            }
        }

        private void dbgridpay_Click(object sender, EventArgs e)
        {
            currowpay = this.BindingContext[dbgridpay.DataSource].Position;
            if (currowpay < 0) return;
            currPaytype = dtpay.DefaultView[currowpay]["付款方式"].ToString();
            currPayNo = dtpay.DefaultView[currowpay]["支付号"].ToString();
            currPayTotal = dtpay.DefaultView[currowpay]["支付金额"].ToString();
            payfound = true;

            //cmbPaytype.Text = currPaytype;
            //txtPayNo.Text = currPayNo;
            //txtPayTotal.Text = currPayTotal;
            //txtPayTotal.Focus();
        }

        private void dbgrid_Click(object sender, EventArgs e)
        {
            currow = this.BindingContext[dbgrid.DataSource].Position;
            if (currow < 0) return;
            currPluID = dt.DefaultView[currow]["商品ID"].ToString();
            currPluCode = dt.DefaultView[currow]["商品编码"].ToString();
            currPluName = dt.DefaultView[currow]["商品名称"].ToString();
            currUnit = dt.DefaultView[currow]["单位"].ToString();
            currCount = float.Parse(dt.DefaultView[currow]["批发数量"].ToString());
            currPfPrice = float.Parse(dt.DefaultView[currow]["批发价格"].ToString());
            currPluType = dt.DefaultView[currow]["类型"].ToString();


            txtPluCode.Text = currPluCode;
            lblpluname.Text = currPluName;
            lblpluname.ForeColor = Color.Blue;
            txtPackCount.Text = "";
            txtPfCount.Text = currCount.ToString();
            txtPfPrice.Text = currPfPrice.ToString();
            // 0-正品  1-赠品  2-促销品  3-不良品
            btnPluType.Text = currPluType;

            rowfound = true;
            txtPfCount.Focus();

            //将txtJhCount全选
            txtPfCount.SelectAll();
        }

        private void gridsel_Click(object sender, EventArgs e)
        {
            currowsel = this.BindingContext[gridsel.DataSource].Position;
            if (currowsel < 0) return;
            txtEtpCode.Text = dtetp.DefaultView[currowsel]["客户编码"].ToString() + "-"
                  + dtetp.DefaultView[currowsel]["客户名称"].ToString();
            curretptype = dtetp.DefaultView[currowsel]["类型"].ToString();
            txtEtpCode.Focus();
        }

        private void gridselUser_Click(object sender, EventArgs e)
        {
            currowsel = this.BindingContext[gridselUser.DataSource].Position;
            if (currowsel < 0) return;
            txtSender.Text = dtuser.DefaultView[currowsel]["员工编码"].ToString() + "-"
                  + dtuser.DefaultView[currowsel]["员工姓名"].ToString();
            currEmpId = dtuser.DefaultView[currowsel]["员工ID"].ToString();
            txtSender.Focus();
        }

        private void gridtruck_Click(object sender, EventArgs e)
        {
            currowsel = this.BindingContext[gridtruck.DataSource].Position;
            if (currowsel < 0) return;
            txtTruck.Text = dttruck.DefaultView[currowsel]["车牌号"].ToString();
            txtTruck.Focus();
        }

        private void txtPayTotal_GotFocus(object sender, EventArgs e)
        {
            //进行金额合计
            payedtotal = 0;
            foreach (DataRow dr in dtpay.Rows)
            {
                payedtotal = payedtotal + float.Parse(dr["支付金额"].ToString());
            }

            txtPayTotal.Text = (float.Parse(txtSsTotal.Text) - payedtotal).ToString();
            txtPayTotal.SelectAll();
        }

        private void txtPayTotal_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8
                && e.KeyChar != (char)13 && e.KeyChar != '.')
            {
                e.Handled = true;
            }
        }

        private void txtPfPrice_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                txtPfCount.Focus();
                txtPfCount.SelectAll();
            }
        }

        private void gridList_DoubleClick(object sender, EventArgs e)
        {
            currowsel = this.BindingContext[gridList.DataSource].Position;
            if (currowsel < 0) return;
            currBillNo = dtlist.DefaultView[currowsel]["单号"].ToString();
            curretp = dtlist.DefaultView[currowsel]["客户"].ToString();
            pnlshow.Visible = true;
            pnlHead.Visible = false;
            btnRefresh.Text = "返回";

            //进行商品信息查询
            if (!CanDoNext)
            {
                return;
            }
            CanDoNext = false;

            try
            {
                string sRtnMsg = string.Empty;
                StoreRf rf = new StoreRf();
                bool bResult = rf.QryWslPfXsBodyInfo(currBillNo, out sRtnMsg);
                if (!bResult)
                {
                    MessageBox.Show("获取批发商品明细失败！", "提示", MessageBoxButtons.OK,
                      MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
                    return;
                }

                string CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                string FileName = CurrentPath + "\\PfDataBody.xml";
                if (File.Exists(FileName))
                {
                    FileStream fs = File.OpenRead(FileName);
                    try
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        string sWslBodyXML = System.Text.Encoding.Default.GetString(buffer, 0, buffer.Length);
                        List<WslPfXsBodyInfo> lsXsBodyInfo = JsonConvert.DeserializeObject<List<WslPfXsBodyInfo>>(sWslBodyXML);
                        if (dtshow != null && dtshow.Rows.Count > 0) dtshow.Clear();
                        foreach (WslPfXsBodyInfo xsbodyinfo in lsXsBodyInfo)
                        {
                            //新建行
                            DataRow row = dtshow.NewRow();
                            //行赋值
                            row["商品ID"] = xsbodyinfo.PluID.ToString();
                            row["商品编码"] = xsbodyinfo.PluCode;
                            row["商品名称"] = xsbodyinfo.PluName;
                            row["单位"] = xsbodyinfo.Unit;
                            row["批发数量"] = xsbodyinfo.PfCount;
                            row["批发价格"] = xsbodyinfo.PfPrice;

                            if (xsbodyinfo.PluType == "0")
                            {
                                row["类型"]  = "正品";
                            }
                            else if (xsbodyinfo.PluType == "1")
                            {
                                row["类型"]  = "赠品";
                            }
                            //添加行
                            dtshow.Rows.Add(row);
                        }
                    }
                    finally
                    {
                        fs.Close();
                    }
                }
            }
            finally
            {
                CanDoNext = true;
            }
        }

        private void BillPrint(string sWriteData)
        {
            if (SmartVar.ConnectedBT)
            {
                byte[] CmdBuf1 = new byte[2];
                CmdBuf1[0] = 0x1b;
                CmdBuf1[1] = 0x40;
                SmartVar.myBT.WriteToPort(CmdBuf1, 2);// 初始化打印机
                byte[] CmdBuf = Encoding.Default.GetBytes(sWriteData);
                SmartVar.myBT.WriteToPort(CmdBuf, CmdBuf.Length);

                byte[] CmdBuf2 = new byte[3];
                CmdBuf2[0] = 0x1b;
                CmdBuf2[1] = 0x4a;
                CmdBuf2[2] = 0x10;
                SmartVar.myBT.WriteToPort(CmdBuf2, 3);
            }
        }

        private void btnUpPay_Click(object sender, EventArgs e)
        {
            if (currBillNo == "")
            {
                MessageBox.Show("批发单号为空，不允许上传！", "客户分销", MessageBoxButtons.OK,
                      MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }

            //if (txtSender.Text.Trim() == "" || txtSender.Text.IndexOf('-') <= 0)
            //{
            //    MessageBox.Show("必须选择送货员！", "客户分销", MessageBoxButtons.OK,
            //         MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
            //    return;
            //}

            //if (txtTruck.Text.Trim() == "")
            //{
            //    MessageBox.Show("必须指定车牌！", "客户分销", MessageBoxButtons.OK,
            //         MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
            //    return;
            //}

            //进行批发金额合计
            double fSsTotal = 0;
            foreach (DataRow dr in dtshow.Rows)
            {
                fSsTotal = fSsTotal + Math.Round(float.Parse(dr["批发数量"].ToString())
                    * float.Parse(dr["批发价格"].ToString()) * 100) / 100;
            }
            txtSsTotal.Text = fSsTotal.ToString();

            ////判断是否完成支付
            //payedtotal = 0;
            //foreach (DataRow dr in dtpay.Rows)
            //{
            //    payedtotal = payedtotal + float.Parse(dr["支付金额"].ToString());
            //}

            //if (float.Parse(txtSsTotal.Text) - payedtotal > 0)
            //{
            //    MessageBox.Show("未完成付款，不允许上传！", "客户分销", MessageBoxButtons.OK,
            //          MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
            //    return;
            //}

            DialogResult dialog = MessageBox.Show("确定要上传该批发订单的支付信息吗？", "客户分销", MessageBoxButtons.YesNo,
               MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dialog != DialogResult.Yes)
            {
                return;
            }

            //进行上传
            WslPfXsHead xshead = new WslPfXsHead();
            xshead.BillNo = currBillNo;
            //string sEtpCode = txtEtpCode.Text.Trim();
            //if (sEtpCode.IndexOf('-') > 0)
            //{
            //    xshead.EtpCode = sEtpCode.Substring(0, sEtpCode.IndexOf('-'));
            //}

            xshead.LrDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            xshead.YwyCode = SmartVar.UserCode;
            string sSender = txtSender.Text.Trim();
            if (sSender.IndexOf('-') > 0)
            {
                xshead.ShyCode = sSender.Substring(0, sSender.IndexOf('-'));
            }
            xshead.TrunckNo = txtTruck.Text.Trim();
            //0-批发销售；1-批发退货；2-批发订货； 3-无批发单退货 4-不管库存联销商品批发
            xshead.BillType = "2";
            xshead.RFNO = SmartVar.RFNO;

            int i = 1;
            foreach (DataRow dr in dtpay.Rows)
            {
                WslPfXsPay xspay = new WslPfXsPay();
                xspay.SerialNo = i;
                string sPayType = dr["付款方式"].ToString();
                if (dr["状态"].ToString() == "0")
                {
                    if (sPayType.IndexOf('-') > 0)
                    {
                        xspay.Paytype = sPayType.Substring(0, sPayType.IndexOf('-'));
                    }
                    xspay.PayNo = dr["支付号"].ToString();
                    xspay.PayTotal = float.Parse(dr["支付金额"].ToString());
                    xshead.lstWslPfXsPay.Add(xspay);
                    i = i + 1;
                }
            }

            
            StoreRf rf = new StoreRf();
            string sRtnMsg = string.Empty;
            int iRtnCode = rf.DealWslPfXs(xshead, out sRtnMsg);
            if (iRtnCode == 0)
            {
                btnUpPay.Enabled = false;
                //进行小票打印
                StringBuilder sb = new StringBuilder();
                sb.Append("    肥城达润兴批发订单    \r\n");
                sb.Append("--------------------------\r\n");
                sb.Append("客户：" + curretp + " \r\n");
                sb.Append("业务员：" + txtYwyCode.Text.Trim() + " \r\n");
                sb.Append(" 送货员：" + txtSender.Text.Trim() + " \r\n");
                sb.Append("车牌号：" + txtTruck.Text.Trim() + " \r\n");
                foreach (DataRow dr in dtshow.Rows)
                {
                    sb.Append("品名：" + dr["商品编码"].ToString() + " " + dr["商品名称"].ToString() + "\r\n");
                    sb.Append(" 单位：" + dr["单位"].ToString()
                        + " 数量：" + dr["批发数量"].ToString()
                        + " 价格：" + dr["批发价格"].ToString() + "\r\n");
                }
                sb.Append("-------------------------\r\n");
                sb.Append("合计应收：" + txtSsTotal.Text.Trim() + "\r\n");
                foreach (DataRow dr in dtpay.Rows)
                {
                    sb.Append("支付方式：" + dr["付款方式"].ToString() + " " + dr["支付金额"].ToString() + "\r\n");
                }
                sb.Append(" \r\n");
                sb.Append(" \r\n");
                string sWriteData = sb.ToString();

                BillPrint(sWriteData);

                dtshow.Clear();
                dtshow = null;
                dtpay.Clear();
                dtpay = null;

                xshead.lstWslPfXsBody.Clear();
                xshead.lstWslPfXsBody = null;
                xshead.lstWslPfXsPay.Clear();
                xshead.lstWslPfXsPay = null;
                xshead = null;

                txtEtpCode.Text = "";
                txtSender.Text = "";
                txtTruck.Text = "";

                MessageBox.Show("上传批发订单支付信息成功！", "客户分销", MessageBoxButtons.OK,
                     MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }
            else
            {
                MessageBox.Show("上传批发订单支付信息失败！" + (char)13 + sRtnMsg, "客户分销", MessageBoxButtons.OK,
                    MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
                return;
            }
        }
    }
}